package com.chockqiu.html.fontface;

import android.text.Editable;
import android.text.Html;

import org.xml.sax.XMLReader;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author Administrator
 */
public class HtmlTagRegister implements Html.TagHandler {

    private final HashMap<String, String> attributes = new HashMap<>();
    private final List<HtmlTagHandler> mSpecialTag = new ArrayList<>();

    public void registerHtmlTag(HtmlTagHandler st) {
        if (st != null) {
            mSpecialTag.add(st);
        }
    }

    public void unRegisterHtmlTag(HtmlTagHandler st) {
        if (st != null) {
            mSpecialTag.remove(st);
        }
    }

    @Override
    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
        try {
            processAttributes(xmlReader);
            for (int i = 0; i < mSpecialTag.size(); i++) {
                HtmlTagHandler mSpecialHtmlTag = mSpecialTag.get(i);
                if (tag.equalsIgnoreCase(mSpecialHtmlTag.getTagName())) {
                    mSpecialHtmlTag.handleTag(opening, tag, output, attributes);
                }
            }
            if (!opening) {
                attributes.clear();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void processAttributes(final XMLReader xmlReader) {
        try {
            Field elementField = xmlReader.getClass().getDeclaredField("theNewElement");
            elementField.setAccessible(true);
            Object element = elementField.get(xmlReader);
            Field attsField = element.getClass().getDeclaredField("theAtts");
            attsField.setAccessible(true);
            Object atts = attsField.get(element);
            Field dataField = atts.getClass().getDeclaredField("data");
            dataField.setAccessible(true);
            String[] data = (String[]) dataField.get(atts);
            Field lengthField = atts.getClass().getDeclaredField("length");
            lengthField.setAccessible(true);
            int len = (Integer) lengthField.get(atts);

            for (int i = 0; i < len; i++) {
                attributes.put(data[i * 5 + 1], data[i * 5 + 4]);
            }
        } catch (Exception e) {
            //IGNORE
        }
    }
}
